import Koa from 'koa';
import koaJwt from 'koa-jwt';
import KoaCors from '@koa/cors';
import { useKoaServer } from 'routing-controllers';
import { jwtconfig, serverconfig, unlesspath } from './config/app.config';
import { Moment } from './utils/format';

export function AppServer() {
  const app = new Koa();

  // 允许跨域设置
  app.use(KoaCors());

  // 401 handling
  app.use(async (ctx, next) => {
    try {
      return await next();
    } catch (err) {
      if (err.status === 401) {
        ctx.body = {
          code: err.status,
          message: err.originalError ? err.originalError.message : err.message
        };
      } else {
        throw err;
      }
    }
  });

  // 启用jwt
  app.use(koaJwt({ secret: jwtconfig.secret }).unless({ path: unlesspath }));

  // 注册服务
  useKoaServer(app, serverconfig.options);

  // 端口监听
  app.listen(serverconfig.port, () => {
    console.log(`server is running: http://localhost:${serverconfig.port}`);
    console.log('当前时间是:', new Moment().format());
  });
}
